public class Solution794 {

    private int[] getCount(String[] board){
        int xCount = 0, oCount = 0;
        for (String str : board) {
            for (int i = 0; i < str.length(); i++) {
                char c = str.charAt(i);
                if(c == 'X'){
                    xCount++;
                }
                else if(c == 'O'){
                    oCount++;
                }
            }
        }
        return new int[]{xCount, oCount};
    }

    private boolean travel(String[] board, char target, int x, int y, int xDirect, int yDirect){
        for (int i = 0; i < 3; i++, x+=xDirect, y+=yDirect) {
            if(board[x].charAt(y) != target){
                return false;
            }
        }
        return true;
    }

    private boolean doJudge(String[] board, char target){
        return (travel(board, target, 0, 0, 1, 1)||
                travel(board, target, 0, 0, 0, 1)||
                travel(board, target, 0, 0, 1, 0)||
                travel(board, target, 0, 1, 1, 0)||
                travel(board, target, 0, 2, 1, 0)||
                travel(board, target, 1, 0, 0, 1)||
                travel(board, target, 2, 0, 0, 1)||
                travel(board, target, 2, 0, -1, 1)
        );
    }

    public boolean validTicTacToe(String[] board) {
        int[] count = getCount(board);
        if(doJudge(board, 'X')){
            return count[0] == count[1] + 1;
        }
        else if(doJudge(board, 'O')){
            return count[0] == count[1];
        }
        return (count[0] == count[1] + 1 || count[0] == count[1]);
    }

    public static void main(String[] args) {
        Solution794 s = new Solution794();
        s.validTicTacToe(new String[]{"OOO","XXO","XXX"});
    }
}
